package com.serverapk.exceptionHandler;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import com.serverapk.MainActivity;
import com.serverapk.para.Common;
import com.serverapk.util.L;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by corner on 2017/5/4.
 * 捕获全局异常 当应用异常导致崩溃 一秒后自动重启应用
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static String Tag = CrashHandler.class.getSimpleName();

    private static CrashHandler mInstance = new CrashHandler();

    private Thread.UncaughtExceptionHandler mDefaultHandler = null;

    private Context mContext = null;

    private Map<String, String> infos = new HashMap<String, String>();

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return mInstance;
    }

    public void init(Context context) {
        this.mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(mInstance);
    }

    public boolean handleException(Throwable ex) {
        try {
            if (ex == null) {
                return false;
            }
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    Toast.makeText(mContext, "程序出现异常即将退出", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }.start();
            collectErrors();
            saveErrors(ex);
            return true;
        } catch (Exception e) {
            return true;
        }

    }

    private String saveErrors(Throwable ex) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            stringBuilder.append(key + "=" + value + "\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        stringBuilder.append(result);
        try {
            long timestamp = System.currentTimeMillis();
            String time = dateFormat.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = Common.crash_path+"/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(stringBuilder.toString().getBytes());
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
            L.d(Tag, "SaveErrors:" + e.getMessage());
        }
        return null;
    }

    private void collectErrors() {
        PackageManager packageManager = null;
        try {
            packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (packageInfo != null) {
                String versionName = packageInfo.versionName == null ? "null" : packageInfo.versionName;
                String versionCode = packageInfo.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            L.d(Tag, "CollectError(PackageInfo):" + e.getMessage());
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                infos.put(field.getName(), field.get(null).toString());
            } catch (IllegalAccessException e) {
                L.d(Tag, "CollectError(Field):" + e.getMessage());
            }
        }
    }

    @Override
    public void uncaughtException(Thread thread, final Throwable ex) {

        L.e("全局捕获的异常信息 ： " + ex.toString());

        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(2000);

            } catch (Exception e) {
                L.d(Tag, "Thread Sleep Exception:" + e.getMessage());
            }

            new Thread() {
                @Override
                public void run() {

                    Intent intent = new Intent(mContext, MainActivity.class);
                    PendingIntent restartIntent = PendingIntent.getActivity(mContext, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
                    AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
                    android.os.Process.killProcess(android.os.Process.myPid());
//                ToastUtil.showLong(mContext,"全局捕获的异常信息 ： " + ex.toString());
                }
            }.start();
        }
    }
}